<template>
  <div class="news-container">
 
    <div class="add-section">
      <button @click="openAdd">
        <drawer2 ref="addDrawerRef" @close="handleAddDrawer" @news-added="refreshNewsList">
          手动添加
        </drawer2>
      </button>
    </div>

    <div class="main-layout">
      <div class="news-panel">
        <div class="panel-header">
          <span>共{{ filteredNews.length }}条新闻</span>
        </div>


        <div v-for="(news, index) in paginatedNews" :key="news.id" class="news-item">
          <div class="news-header">
            <div class="source-info">
              <el-tag :type="getTag(news.classReal)?.type" :color="getTag(news.classReal)?.color">
                {{ getTag(news.classReal)?.label }}
              </el-tag>
              <span>{{ news.source }}</span>
              <span class="time">· 由{{ news.updater }}更新</span>
            </div>
            <div class="meta-info">
              <span>{{ news.publishTime }}</span>
              <span :class="statusClass(news.status)">{{ statusText(news.status) }}</span>
            </div>
          </div>


          <div class="news-content">
            <div class="title-section">
              <span :class="categoryClass(news.category)">{{ news.category }}</span>
              <h3 @click="openParticulars(news)">{{ news.newsTitle }}</h3>
            </div>
            <p class="summary">{{ news.summary }}</p>
            <div class="action-section">
              <div class="author-info">
                <span class="icon">{{ news.authorIcon }}</span>
                <span>{{ news.author }}</span>
              </div>
              <div class="actions">
                <button v-if="news.status !== 'published'" @click="addToPending(news.id)">
                  + 加入待发布
                </button>
                <button  @click="openDrawer(news)">
                  编辑
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="filteredNews.length > 0" class="pagination-section">
          <span>共{{ filteredNews.length }}条</span>
          <el-pagination
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="prev, pager, next, jumper, ->, sizes"
            :total="filteredNews.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 右侧待发布列表 -->
      <div class="pending-panel">
        <releaseList ref="releaseRef" :show-bottom-btn="true" />
      </div>
    </div>

    <!-- 抽屉组件 -->
    <Drawer ref="drawerRef" :news-data="selectedNews" @close="handleDrawerClose" />
    <Particulars
      v-if="showParticulars"
      :news-data="selectedDetailNews"
      @close="handleParticularsClose"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import Drawer from '@/components/JournaLism/drawer.vue'
import drawer2 from './drawer2.vue'
import releaseList from './releaseList.vue'
import Particulars from './particulars.vue'
import { getNewsList, updateNews } from '@/API/AllApi'
import { categoryList } from '@/components/JournaLism/category'

const props = defineProps({
  filters: {
    type: Object,
    default: () => ({
      searchText: '',
      newsType: '全部',
      sortBy: '时间降序',
      timeRange: '',
      addMethod: '',
      publishStatus: ''
    })
  }
})

const router = useRouter()

// 响应式数据
const allNews = ref([]) // 存储所有新闻数据
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const drawerRef = ref(null)
const addDrawerRef = ref(null)
const selectedNews = ref(null)
const selectedDetailNews = ref(null)
const showParticulars = ref(false)
const releaseRef = ref(null)

const filteredNews = computed(() => {
  let result = [...allNews.value]
  

  if (props.filters.searchText) {
    const searchLower = props.filters.searchText.toLowerCase()
    result = result.filter(item => 
      item.newsTitle.toLowerCase().includes(searchLower) || 
      item.summary.toLowerCase().includes(searchLower)
    )
  }

  if (props.filters.newsType && props.filters.newsType !== '全部') {
    result = result.filter(item => item.classReal === props.filters.newsType)
  }
  
  if (props.filters.publishStatus && props.filters.publishStatus !== '全部状态') {
    if (props.filters.publishStatus === '已发布') {
      result = result.filter(item => item.status === 'published')
    } else if (props.filters.publishStatus === '草稿') {
      result = result.filter(item => item.status === 'draft')
    }
  }
  
  if (props.filters.addMethod && props.filters.addMethod !== '全部方式') {
    result = result.filter(item => 
      (item.originalData.addMethod || '').includes(props.filters.addMethod)
    )
  }
  
  if (props.filters.timeRange && props.filters.timeRange !== '全部时间') {
    const now = new Date()
    result = result.filter(item => {
      const newsDate = new Date(item.publishTime)
      
      if (props.filters.timeRange === '本周') {
        const weekStart = new Date(now)
        weekStart.setDate(now.getDate() - now.getDay())
        weekStart.setHours(0, 0, 0, 0)
        return newsDate >= weekStart
      } else if (props.filters.timeRange.includes('至')) {
        const [startStr, endStr] = props.filters.timeRange.split('至')
        const startDate = new Date(startStr.trim())
        const endDate = new Date(endStr.trim())
        endDate.setHours(23, 59, 59, 999)
        return newsDate >= startDate && newsDate <= endDate
      }
      return true
    })
  }
  
  if (props.filters.sortBy === '时间升序') {
    result.sort((a, b) => new Date(a.publishTime) - new Date(b.publishTime))
  } else {
    result.sort((a, b) => new Date(b.publishTime) - new Date(a.publishTime))
  }
  
  return result
})

const paginatedNews = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredNews.value.slice(start, end)
})

const fetchNewsList = async () => {
  loading.value = true
  try {
    const result = await getNewsList({
      current: 1,
      currentSize: 9999 
    })
    
    allNews.value = processNewsData(result.data?.records || [])
    currentPage.value = 1 
  } catch (err) {
    console.error('获取新闻列表失败:', err)
    ElMessage.error('获取新闻列表失败，请稍后重试')
    allNews.value = []
  } finally {
    loading.value = false
  }
}

const processNewsData = (rawNews) => {
  return rawNews.map(item => ({
    id: item.id,
    source: item.siteName || '',
    classReal: item.classReal || '',
    updater: item.opPerson || '',
    publishTime: item.newsTime || '',
    status: item.isPublished === 1 ? 'published' : 'draft',
    category: item.classModel || '',
    newsTitle: item.newsTitle || '',
    summary: item.abstractReal || '',
    author: item.newsSource || '',
    authorIcon: item.newsSource?.charAt(0).toUpperCase() || '?',
    originalData: item
  }))
}

// 按钮操作
const openAdd = () => {
  selectedNews.value = null
  addDrawerRef.value?.openDrawer()
}

const handleAddDrawer = () => {
  addDrawerRef.value?.handleCancel()
}

const refreshNewsList = () => {
  fetchNewsList()
}

// 分页操作
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 切换每页数量时回到第一页
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 添加到待发布
const addToPending = async (id) => {
  try {
    const news = allNews.value.find(item => item.id === id)
    if (!news) {
      ElMessage.error('新闻不存在')
      return
    }
    
    const res = await updateNews({ id, isSelect: 1 })
    if (res.code === 200) {
      news.status = 'pending'
      releaseRef.value?.refreshList?.()
      ElMessage.success('新闻加入待发布列表成功')
    } else {
      ElMessage.error(res?.message || '操作失败')
    }
  } catch (err) {
    console.error('加入待发布失败:', err)
    ElMessage.error('操作失败，请稍后重试')
  }
}

const openDrawer = (news) => {
  selectedNews.value = { ...news }
  drawerRef.value?.openDrawer()
}

const handleDrawerClose = () => {
  selectedNews.value = null
}

const openParticulars = (news) => {
  selectedDetailNews.value = { ...news }
  showParticulars.value = true
}

const handleParticularsClose = () => {
  showParticulars.value = false
  selectedDetailNews.value = null
}

const getTag = (classReal) => {
  return categoryList.find(item => item.value === classReal) || {}
}

const statusText = (status) => {
  return { published: '已发布', pending: '待发布', draft: '草稿' }[status] || '草稿'
}

const statusClass = (status) => {
  return {
    'status-published': status === 'published',
    'status-pending': status === 'pending',
    'status-draft': status === 'draft'
  }
}

const categoryClass = (category) => {
  return {
    'category-macro': category === '宏观',
    'category-economy': category === '经济',
    'category-industry': category === '行业'
  }
}


watch(() => props.filters, () => {
  currentPage.value = 1 
}, { deep: true })

onMounted(() => {
  fetchNewsList()
})
</script>

<style scoped>
.news-container {
  padding: 1.25rem;
  background-color: #f9fafb;
  min-height: 100vh;
}

.add-section {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1rem;
  border: 1px dashed #717070;
  margin: 1rem 0;
}

.main-layout {
  display: flex;
  gap: 1.25rem;
}

.news-panel {
  flex: 2;
  background: white;
  border-radius: 0.5rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.pending-panel {
  flex: 1;
}

.panel-header {
  background: linear-gradient(to right, #3b82f6, #60a5fa);
  color: white;
  padding: 1.25rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.news-item {
  padding: 1.25rem;
  border-bottom: 1px solid #f3f4f6;
}

.news-item:last-child {
  border-bottom: none;
}

.news-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.75rem;
}

.source-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.source-info .time {
  color: #6b7280;
  font-size: 0.875rem;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.status-published {
  background-color: #3b82f6;
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 0.375rem;
  font-size: 0.75rem;
}

.status-pending {
  background-color: #ef4444;
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 0.375rem;
  font-size: 0.75rem;
}

.status-draft {
  background-color: #f3f4f6;
  color: #6b7280;
  padding: 0.25rem 0.5rem;
  border-radius: 0.375rem;
  font-size: 0.75rem;
}

.news-content h3 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  cursor: pointer;
  transition: color 0.2s ease;
}

.news-content h3:hover {
  color: #2563eb;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 0.625rem;
  margin-bottom: 0.625rem;
}

.category-macro {
  background-color: #10b981;
  color: white;
  padding: 0.125rem 0.625rem;
  border-radius: 0.375rem;
  font-size: 0.75rem;
  font-weight: 500;
}

.category-economy {
  background-color: #ef4444;
  color: white;
  padding: 0.125rem 0.625rem;
  border-radius: 0.375rem;
  font-size: 0.75rem;
  font-weight: 500;
}

.category-industry {
  background-color: #3b82f6;
  color: white;
  padding: 0.125rem 0.625rem;
  border-radius: 0.375rem;
  font-size: 0.75rem;
  font-weight: 500;
}

.summary {
  color: #4b5563;
  font-size: 1rem;
  margin-bottom: 1rem;
}

.action-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.author-info .icon {
  width: 1.25rem;
  height: 1.25rem;
  background-color: #3b82f6;
  color: white;
  border-radius: 9999px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.75rem;
  line-height: 1;
}

.actions {
  display: flex;
  gap: 0.75rem;
}

.actions button {
  padding: 0.25rem 0.75rem;
  border-radius: 0.375rem;
  cursor: pointer;
  border: none;
  transition: background-color 0.2s ease;
}

.actions button:first-child {
  background-color: #3b82f6;
  color: white;
}

.actions button:first-child:hover {
  background-color: #2563eb;
}

.actions button:last-child {
  background-color: #eff6ff;
  color: #2563eb;
}

.actions button:last-child:hover {
  background-color: #dbeafe;
}

.pagination-section {
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #4b5563;
  font-size: 0.875rem;
  border-top: 1px solid #f3f4f6;
}
</style>